package com.oceansoft.mobile.vote.controller;

import com.oceansoft.mobile.biz.front.controller.OauthController;
import com.oceansoft.mobile.common.base.entity.Result;
import com.oceansoft.mobile.common.util.MD5;
import com.oceansoft.mobile.common.util.StringUtils;
import com.oceansoft.mobile.vote.domain.Tickets;
import com.oceansoft.mobile.vote.domain.VoteInfo;
import com.oceansoft.mobile.vote.service.IVoteService;

import freemarker.template.utility.StringUtil;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhangxl on 2017/12/28.
 */

@Controller
@RequestMapping("vote")
public class VoteController {

    @Resource
    IVoteService voteService;

    /**
     * 进入活动介绍，投票页面(警信通入口)
     * 1 警信通 2 苏州公安微警务 3苏州警方
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "gotoIndexJXT", method = RequestMethod.GET)
    public String gotoIndexJXT(HttpServletRequest request, ModelMap modelMap) {
        String jh = request.getParameter("jh");
        String userid = "";
        if (StringUtils.isNotEmpty(jh) && jh.contains(",")) {
            //
            String md5String = jh.split(",")[1];
            userid = jh.split(",")[0];
            //判断用户合法性
            if (!md5String.equals(new MD5().MD5_1(userid))) {
                modelMap.addAttribute("msg", "用户信息不合法！");
                return "vote/404";
            }
        }
        HttpSession session = request.getSession();
        if (jh == null) {//进入页面时是否有登录信息，没有就从session中获取
            userid = (String) request.getSession().getAttribute("userid");
        } else {
            session.setAttribute("ly", "1");
            session.setAttribute("userid", userid);
            //userid = jh;
        }

        //获取session中存的候选人id
        String ids = (String) session.getAttribute("infoids");
        if (!(ids == null || ids == "")) {
            modelMap.addAttribute("infoids", ids);
        }


        //1、验证是否有openid
        if ("".equals(userid) || userid == null) {
            modelMap.addAttribute("msg", "会话过期，请关闭后重试！");
            return "vote/404";
        }
        //获取累积投票，参与人数
        String tickets = voteService.countAllTickets();
        String persons = voteService.countAllPersons();

        //2、获取当天(自然日)该openid是否投票数
        int i = voteService.countVote(String.valueOf(userid));

        //获取候选人信息.根据编号排序
        List<VoteInfo> voteInfos = voteService.findVoteInfos();

        modelMap.addAttribute("voteInfos", voteInfos);
        modelMap.addAttribute("tickets", tickets);
        modelMap.addAttribute("persons", persons);
        Date date = new Date();
        String str = "2018-01-09 23:59:58";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newDate = new Date();
        try {
            newDate = format.parse(str);
        } catch (Exception e) {
            return "vote/404";
        }

        if (date.getTime() > newDate.getTime()) {
            return "vote/indexE";
        } else {


            //3、如果投票过，只能看页面投票按钮灰掉
            if (i > 0) {
                modelMap.addAttribute("ytp", "1");//ytp:已投票
                return "vote/index";
            }
            //4、如果没有投票过，可以投票
            return "vote/index";
        }
    }

    /**
     * 进入活动介绍，投票页面(苏州公安微警务入口)
     * 1 警信通 2 苏州公安微警务 3苏州警方
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "weixin/gotoIndexWJW", method = RequestMethod.GET)
    public String gotoIndexWJWindex(HttpServletRequest request, ModelMap modelMap) {
        String openid = request.getParameter("openId");//获取用户openid
        String jym = request.getParameter("jym");//获取验证码
        //openid 和验证码不为空
//        System.out.println("==判断用户合法性===openid----"+openid+"===jym---"+jym);
        if (StringUtils.isNotEmpty(jym) && StringUtils.isNotEmpty(openid)) {
            //判断用户合法性
            if (!jym.equals(new MD5().MD5_1(openid))) {// 验证码 不等于openid 转码
                modelMap.addAttribute("msg", "用户信息不合法！");
//                System.out.println("-======用户信息不合法！=======-");
                return "vote/404";
            }
            HttpSession session = request.getSession();
            session.setAttribute("openIdwjw", openid);
            System.out.println("==openIdwjw==" + openid);
            return "redirect:" + "http://wjw.szgaj.cn/dszwx/vote/weixin/gotoIndexWJWindex?merid=1070";
        }
        System.out.println("-======用户信息不完整！=======-");
        return "redirect:" + "http://wjw.szgaj.cn/szgawx/oauth/getOpenId?page=http://wjw.szgaj.cn/dszwx/vote/weixin/gotoIndexWJW?merid=1070&source=szgawx";
    }


    @RequestMapping(value = "weixin/gotoIndexWJWindex", method = RequestMethod.GET)
    public String gotoIndexWJW(HttpServletRequest request, ModelMap modelMap) {
        String openid = (String) request.getSession().getAttribute("openIdwjw");
        try {
            String from = "";
            String isappinstalled = "";
            from = request.getParameter("from");
            isappinstalled = request.getParameter("isappinstalled");
            if (!"".equals(from) && null != from && !"".equals(isappinstalled) && null != isappinstalled) {
                return "redirect:" + "http://wjw.szgaj.cn/szgawx/oauth/getOpenId?page=http://wjw.szgaj.cn/dszwx/vote/weixin/gotoIndexWJW?merid=1070&source=szgawx";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println("进页面openidwjw===="+openid);
        if (openid == null) {
            return "redirect:" + "http://wjw.szgaj.cn/szgawx/oauth/getOpenId?page=http://wjw.szgaj.cn/dszwx/vote/weixin/gotoIndexWJW?merid=1070&source=szgawx";
//            System.out.println("进页面sessionopenidwjw===="+openid);
        }
        String userid = "";
        HttpSession session = request.getSession();
        if (openid == null) {//进入页面时是否有登录信息，没有就从session中获取
            userid = (String) request.getSession().getAttribute("userid");
        } else {
            session.setAttribute("ly", "2");
            session.setAttribute("userid", openid);
            userid = openid;
        }

        //获取session中存的候选人id
        String ids = (String) session.getAttribute("infoids");
        if (!(ids == null || ids == "")) {
            modelMap.addAttribute("infoids", ids);
        }
//        System.out.println("==userid=="+userid);

        //1、验证是否有openid
        if ("".equals(userid) || userid == null) {
            modelMap.addAttribute("msg", "会话过期，请关闭后重试！");
            return "vote/404";
        }
        //获取累积投票，参与人数
        String tickets = voteService.countAllTickets();
//        String persons = voteService.countAllPersons();
//        System.out.println("==tickets=="+tickets);
//        System.out.println("==persons=="+persons);
        //2、获取当天(自然日)该openid是否投票数
        int i = voteService.countVote(String.valueOf(userid));

        //获取候选人信息.根据编号排序
        List<VoteInfo> voteInfos = voteService.findVoteInfos();
//        System.out.println("==VoteInfo=="+voteInfos.toString());
        modelMap.addAttribute("voteInfos", voteInfos);
        modelMap.addAttribute("tickets", tickets);
//        modelMap.addAttribute("persons", persons);
        modelMap.addAttribute("gotoIndex", "wjw");
//        System.out.println("countwjw===="+i);
//        System.out.println("openid===="+userid);
        Date date = new Date();
        String str = "2018-01-21 23:59:58";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newDate = new Date();
        try {
            newDate = format.parse(str);
        } catch (Exception e) {
            return "vote/404";
        }

        if (date.getTime() > newDate.getTime()) {
            return "vote/indexEnd";
        }
        //3、如果投票过，只能看页面投票按钮灰掉
        if (i > 0) {
            modelMap.addAttribute("ytp", "1");//ytp:已投票
            return "vote/index";
        }
        System.out.println("==end==");
        //4、如果没有投票过，可以投票
        return "vote/index";
    }

    /**
     * 进入活动介绍，投票页面(苏州警方入口)
     * 1 警信通 2 苏州公安微警务 3苏州警方
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "weixin/gotoIndexJF", method = RequestMethod.GET)
    public String gotoIndexJF(HttpServletRequest request, ModelMap modelMap) {
        String openid = request.getParameter("openId");
//        String openid = "zwj";
//        System.out.println("进页面openidjf===="+openid);
        if (openid == null) {
            openid = (String) request.getSession().getAttribute("openIdjf");
//            System.out.println("进页面sessionopenidjf===="+openid);
        }
        String userid = "";
        HttpSession session = request.getSession();
        if (openid == null) {//进入页面时是否有登录信息，没有就从session中获取
            userid = (String) request.getSession().getAttribute("userid");
        } else {
            session.setAttribute("ly", "3");
            session.setAttribute("userid", openid);
            userid = openid;
        }

        //获取session中存的候选人id
        String ids = (String) session.getAttribute("infoids");
        if (!(ids == null || ids == "")) {
            modelMap.addAttribute("infoids", ids);
        }


        //1、验证是否有openid
        if ("".equals(userid) || userid == null) {
            modelMap.addAttribute("msg", "会话过期，请关闭后重试！");
            return "vote/404";
        }
        //获取累积投票，参与人数
        String tickets = voteService.countAllTickets();
//        String persons = voteService.countAllPersons();

        //2、获取当天(自然日)该openid是否投票数
        int i = voteService.countVote(String.valueOf(userid));

        //获取候选人信息.根据编号排序
        List<VoteInfo> voteInfos = voteService.findVoteInfos();

        modelMap.addAttribute("voteInfos", voteInfos);
        modelMap.addAttribute("tickets", tickets);
//        modelMap.addAttribute("persons", persons);
        modelMap.addAttribute("gotoIndex", "jf");
//        System.out.println("countjf===="+i);
//        System.out.println("openid===="+userid);
        Date date = new Date();
        String str = "2018-01-21 23:59:58";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newDate = new Date();
        try {
            newDate = format.parse(str);
        } catch (Exception e) {
            return "vote/404";
        }

        if (date.getTime() > newDate.getTime()) {
            return "vote/indexEnd";
        }
        //3、如果投票过，只能看页面投票按钮灰掉
        if (i > 0) {
            modelMap.addAttribute("ytp", "1");//ytp:已投票
            return "vote/index";
        }
        //4、如果没有投票过，可以投票
        return "vote/index";
    }

    /**
     * 投票成功后
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "endVote", method = RequestMethod.GET)
    public String endVote(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        modelMap.addAttribute("ytp", "1");//ytp:已投票

        return "vote/index";
    }

    /**
     * 显示候选人详细信息
     *
     * @param request
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "details/{id}", method = RequestMethod.GET)
    public String getDetails(HttpServletRequest request, @PathVariable("id") String id, ModelMap modelMap) {
        String rank = request.getParameter("rank");
        String source = request.getParameter("source");
        VoteInfo voteInfo = voteService.getVoteInfoById(id);
        voteInfo.setRank(rank);
        modelMap.addAttribute("voteinfo", voteInfo);
        modelMap.addAttribute("source", source);
        return "vote/details";
    }


    /**
     * 投票方法
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "uservote", method = RequestMethod.POST)
    public Result uservote(HttpServletRequest request, HttpServletResponse response) {
        //从session获取投票来源  1 警信通 2 苏州公安微警务 3苏州警方
        HttpSession session = request.getSession();
        String ly = (String) session.getAttribute("ly");
        String userid = (String) session.getAttribute("userid");//投票人信息
//        userid = "zwj";
        if (userid == null) {
            return new Result(false, "信息过期，请重新进入页面!");
        }
        Date date = new Date();
        String str = "2018-01-21 23:59:58";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date newDate = new Date();
        try {
            newDate = format.parse(str);
        } catch (Exception e) {
            return new Result(false, "信息过期，请重新进入页面!");
        }

        if (date.getTime() > newDate.getTime()) {
            return new Result(false, "投票已结束!");
        }
        //获取投票人选择的id
        String infoids = request.getParameter("infoids");
        String[] s = infoids.split(",");
        Tickets ticket = new Tickets();
        if (s.length > 10) {
            return new Result(false, "选票数目过多!");
        }

        int count = voteService.countVote(userid);
        if (count > 0) {
            return new Result(true, "您已投过票，谢谢!");
        } else {
            for (int i = 0; i < s.length; i++) {
                if (i > 0 && s[i].equals(s[i - 1])) {
                    break;
                }
                ticket.setCreatetime(new Date());
                ticket.setInfoid(s[i]);
                ticket.setLy(ly);//1 警信通 2 苏州公安微警务 3苏州警方
                ticket.setUserid(userid);
                voteService.userVote(ticket);
            }
            return new Result(true, "投票成功!");
        }

    }


    /**
     * 选择的候选id存入session
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "savesession", method = RequestMethod.POST)
    public Result saveSession(HttpServletRequest request, HttpServletResponse response) {
        String infoids = request.getParameter("infoids");
        HttpSession session = request.getSession();
        session.setAttribute("infoids", infoids);
        return new Result();
    }

    @ResponseBody
    @RequestMapping(value = "ticket")
    public Result ticket(HttpServletRequest request, HttpServletResponse response) {
        List<Tickets> list = voteService.findTicket();
        String[] num = {"45", "51"};


        for (int i = 150; i < 900; i++) {
            List<Tickets> newlist = new ArrayList<>();
            for (int x = 0; x < num.length; x++) {
                Tickets t = new Tickets();
                t.setInfoid(num[x]);
                newlist.add(t);
            }
            String pol = list.get(i).getUserid();
            if (pol != null) {
                List<Tickets> tic = voteService.findDetail(pol);
                for (Tickets tt : newlist) {
                    tt.setUserid(pol);
                    tt.setCreatetime(tic.get(0).getCreatetime());
                    tt.setLy("1");
                }
                newlist.removeAll(tic);
                for (int y = 0; y < 2; y++) {
                    if (y < newlist.size()) {
                        Tickets ttt = newlist.get(y);
                        voteService.userVote(newlist.get(y));
                    }
                }
            }

        }
        return new Result();
    }


    @RequestMapping(value = "editInfo")
    public String editInfo(HttpServletRequest request, Model model) {
        List<VoteInfo> list = voteService.getVoteInfoList();
        model.addAttribute("vote", list);
        return "vote/editInfo";
    }

    @RequestMapping(value = "edit")
    public String edit(HttpServletRequest request, Model model) {
        String dbid = request.getParameter("id");
        VoteInfo voteInfo = voteService.getVoteInfoById(dbid);
        model.addAttribute("vote", voteInfo);
        return "vote/edit";
    }

    @ResponseBody
    @RequestMapping(value = "save")
    public Result save(HttpServletRequest request) {
        return voteService.update(request);
    }

}
